package com.wy.controller.wy;

import com.wy.constants.CommonConstants;
import com.wy.model.sys.PageResult;
import com.wy.model.sys.RepairEntity;
import com.wy.model.sys.UserEntity;
import com.wy.service.sys.RoleService;
import com.wy.service.sys.UserService;
import com.wy.service.wy.RepairService;
import com.wy.utils.BaseResponseInfo;
import com.wy.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


@RestController
@RequestMapping("/repairs")
@Api(value="API - RepairController",tags={"报修管理"})
public class RepairController {

    private Logger logger = LoggerFactory.getLogger(RepairController.class);

    @Resource(name = "repairServiceImpl")
    private RepairService repairService;

    @Resource(name = "userServiceImpl")
    private UserService userService;

    @Resource(name = "roleServiceImpl")
    private RoleService roleService;
    /**
     * 获取报修列表数据
     * 需要根据权限来显示列表数据
     * 1.普通的住户，只能看到自己提的报修
     * 2.管理员可以看到，所有的报修
     * 3.小区工作人员，只能看到本小区的报修
     * 4.小区的维修人员，只能看到指派给他的报修
     * @param pageSize
     * @param page
     * @param type
     * @param content
     * @param status
     * @param keys
     * @param startTime
     * @param finishTime
     * @return
     */
    @GetMapping("")
    @ApiOperation(value="repairList",notes="")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", required = false,dataType = "Int", paramType = "query", defaultValue = "10"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = false,dataType = "Int", paramType = "query",defaultValue = "1"),
            @ApiImplicitParam(name = "content", value = "内容", required = false,dataType = "String", paramType = "query",defaultValue = ""),
            @ApiImplicitParam(name = "type", value = "报修类型：1水电煤气，2家电家具，3电梯，4门禁，5公共设施，6物业设备，7其他报修", required = false,dataType = "String", paramType = "query",defaultValue = ""),
            @ApiImplicitParam(name = "status", value = "状态:0未处理，1处理中，2已处理，3已取消", required = false,dataType = "String", paramType = "query",defaultValue = ""),
            @ApiImplicitParam(name = "startTime", value = "创建时间（开始）", required = false,dataType = "String", paramType = "query",defaultValue = ""),
            @ApiImplicitParam(name = "finishTime", value = "创建时间（结束）", required = false,dataType = "String", paramType = "query",defaultValue = ""),
            @ApiImplicitParam(name = "keys", value = "关键词", required = false,dataType = "String", paramType = "query",defaultValue = ""),
            @ApiImplicitParam(name = "uid", value = "用户id", required = false,dataType = "Int", paramType = "query",defaultValue = ""),
            @ApiImplicitParam(name = "soon", value = "尽快", required = false,dataType = "String", paramType = "query",defaultValue = "")
    })
    public PageResult repairList(HttpServletRequest request, int pageSize, int page, String type, String content, String status,
                                 String keys, String startTime, String finishTime, Integer uid, String soon){
        List<String> rids = new ArrayList<>();
        UserEntity userEntity = userService.getUserByLoginName(request.getUserPrincipal().getName());
        if(null != userEntity) {
            String rid = userEntity.getRid();
            if(!StringUtils.isEmpty(rid)){
                List list = Arrays.asList(rid.split(","));
                rids = new ArrayList(list);
            }
        }
        Integer ext1 = null;
        PageResult pageResult = new PageResult();
        if("admin".equals(userEntity.getLoginName())) {
            rids = new ArrayList<>();
        }else{
            rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
            //获取当前用户的角色
            List<String>  roleNameList = roleService.getRolesByUserId(userEntity.getId());
            if(null == roleNameList || roleNameList.size() == 0) {
                return pageResult;
            }

            //如果是维修员角色，只能看到分配给自己的报修
            if(roleNameList.contains(CommonConstants.ROLE_MAINTENANCE)) {
                ext1 = userEntity.getId();
                uid = null;
            }else if(roleNameList.contains(CommonConstants.ROLE_APP)) {
                //判断用户角色，如果是业主类型，则只能看到自己的报修 uid 必填
                ext1 = null;
                uid = userEntity.getId();
            }else{
                //其他人员可以看到本小区的报修
            }

        }
        pageResult.setData(repairService.repairList(pageSize, pageSize * page, type, content, status, keys,
                startTime, finishTime, uid, soon,rids,ext1));
        pageResult.setTotalCount(repairService.repairSize(pageSize, pageSize * page, type, content, status, keys,
                startTime, finishTime, uid, soon,rids,ext1));
        return pageResult;
    }

    /**
     *新增报修
     * @param repairEntity
     * @return
     */
    @PostMapping("/repair")
    @ApiOperation(value="insertRepair",notes="新增报修")
    public BaseResponseInfo insertRepair(HttpServletRequest request, @RequestBody  RepairEntity repairEntity){
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        Map<String,Object> map = new HashMap<>();
        if(StringUtils.isEmpty(repairEntity.getContent())) {
            map.put("message","报修内容不能为空！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }
        if(StringUtils.isEmpty(repairEntity.getRepairType())) {
            map.put("message","报修类型不能为空！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }
        if(StringUtils.isEmpty(repairEntity.getContacts())) {
            map.put("message","联系人姓名不能为空！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }
        if(StringUtils.isEmpty(repairEntity.getPhone())) {
            map.put("message","联系电话不能为空！");
            baseResponseInfo.code = 500;
            baseResponseInfo.data = map;
            return baseResponseInfo;
        }
        repairEntity.setStatus(0);//0 未处理，1处理中，2已处理
        repairEntity.setOperator(request.getUserPrincipal().getName()); //当前处理人
        repairEntity.setStartTime(new Date());

        repairEntity.setImg1(FileUtil.getFileName(repairEntity.getImg1()));
        repairEntity.setImg2(FileUtil.getFileName(repairEntity.getImg2()));
        repairEntity.setImg3(FileUtil.getFileName(repairEntity.getImg3()));
        repairEntity.setImg4(FileUtil.getFileName(repairEntity.getImg4()));
        repairEntity.setImg5(FileUtil.getFileName(repairEntity.getImg5()));
        repairEntity.setImg6(FileUtil.getFileName(repairEntity.getImg6()));

        repairService.insertRepair(repairEntity);
        return baseResponseInfo;
    }

    /**
     * 修改报修信息
     * @param repairEntity
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    @ApiOperation(value="updateRepair",notes="修改报修")
    public RepairEntity updateRepair(HttpServletRequest request,@RequestBody RepairEntity repairEntity ,@PathVariable int id){
        if(repairEntity.getId() == id){
            repairEntity.setOperator(request.getUserPrincipal().getName());
            repairEntity.setImg1(FileUtil.getFileName(repairEntity.getImg1()));
            repairEntity.setImg2(FileUtil.getFileName(repairEntity.getImg2()));
            repairEntity.setImg3(FileUtil.getFileName(repairEntity.getImg3()));
            repairEntity.setImg4(FileUtil.getFileName(repairEntity.getImg4()));
            repairEntity.setImg5(FileUtil.getFileName(repairEntity.getImg5()));
            repairEntity.setImg6(FileUtil.getFileName(repairEntity.getImg6()));
            repairService.updateRepair(repairEntity);
        }
        return repairEntity;
    }

    @DeleteMapping("/del")
    @ApiOperation(value="deleteNotice",notes="删除报修")
    public void  delRepair(@RequestBody List<String> repairsIds){
        repairService.delRepair(repairsIds);
    }

    /**
     * 根据报修id获取报修日志记录
     * @return
     */
    @GetMapping("/logs")
    public BaseResponseInfo getRepairLogList(Integer repairId){
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        baseResponseInfo.data = repairService.getRepairLogList(repairId);
        return baseResponseInfo;
    }

    /**
     * 指派保修单到指定的用户
     * @param repairId
     * @param userId
     * @return
     */
    @PostMapping("/assign")
    public BaseResponseInfo assignRepairBill(HttpServletRequest request,Integer repairId,Integer userId) {
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        baseResponseInfo.data = repairService.assignRepairBill(request.getUserPrincipal().getName(),repairId,userId);
        return baseResponseInfo;
    }

    /**
     * 维修员返单
     * @param repairId
     * @return
     */
    @PostMapping("/reassign")
    public BaseResponseInfo reassignRepairBill(Integer repairId) {
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        baseResponseInfo.data = repairService.reassignRepairBill(repairId);
        return baseResponseInfo;
    }

    /**
     * 维修处理完成
     * @param repairId
     * @param remark 处理说明
     * @return
     */
    @PostMapping("/done")
    public BaseResponseInfo dealRepairBill(HttpServletRequest request,Integer repairId,String remark) {
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        UserEntity userEntity = userService.getUserByLoginName(request.getUserPrincipal().getName());
        baseResponseInfo.data = repairService.dealRepairBill(repairId,userEntity.getId(),remark);
        return baseResponseInfo;
    }

}
